﻿using Gym.Application.Common.Interfaces;
using Gym.Domain.Common.EventualConsistency;
using Gym.Domain.ParticipantAggregate;
using Gym.Domain.SessionAggregate.Events;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gym.Application.Participants.Events
{
    public class SessionCanceledEventHandler : INotificationHandler<SessionCanceledEvent>
    {
        private readonly IParticipantsRepository _participantsRepository;

        public SessionCanceledEventHandler(IParticipantsRepository participantsRepository)
        {
            _participantsRepository = participantsRepository;
        }

        public async Task Handle(SessionCanceledEvent notification, CancellationToken cancellationToken)
        {
            List<Participant> participants = await _participantsRepository.ListByIdsAsync(notification.Session.GetParticipantIds());

            participants.ForEach(participant =>
            {
                var removeFromScheduleResult = participant.RemoveFromSchedule(notification.Session);
                if(removeFromScheduleResult.IsError)
                {
                    throw new EventualConsistencyException(
                        SessionCanceledEvent.TrainerScheduleUpdateFailed,
                        removeFromScheduleResult.Errors);
                }
            });

            await _participantsRepository.UpdateRangeAsync(participants);
        }
    }
}
